'use client'

import React, { useState, useEffect } from 'react';
import MainLayout from '@/components/layout/MainLayout';
import ArtworkCard from '@/components/works/ArtworkCard';
import { IArtwork } from '@/types/artwork';
import artworks from '@/data/works.json';

const Gallery: React.FC = () => {
  const [works, setWorks] = useState<IArtwork[]>([]);
  const [filteredWorks, setFilteredWorks] = useState<IArtwork[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('');
  const [selectedArtist, setSelectedArtist] = useState('');
  const [categories, setCategories] = useState<string[]>([]);
  const [artists, setArtists] = useState<string[]>([]);

  // 初始化数据
  useEffect(() => {
    const allWorks = artworks as IArtwork[];
    setWorks(allWorks);
    setFilteredWorks(allWorks);

    // 提取所有分类
    const allCategories = Array.from(new Set(allWorks.flatMap((work) => work.category)));
    setCategories(allCategories);

    // 提取所有艺术家
    const allArtists = Array.from(new Set(allWorks.map((work) => work.artist)));
    setArtists(allArtists);

    // 从URL参数中获取筛选条件
    if (typeof window !== 'undefined') {
      const urlParams = new URLSearchParams(window.location.search);
      const categoryParam = urlParams.get('category');
      if (categoryParam) {
        setSelectedCategory(categoryParam);
      }
    }
  }, []);

  // 处理搜索和筛选
  useEffect(() => {
    let result = [...works];

    // 按搜索词筛选
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        (work) =>
          work.title.toLowerCase().includes(term) ||
          work.artist.toLowerCase().includes(term)
      );
    }

    // 按分类筛选
    if (selectedCategory) {
      result = result.filter((work) => work.category.includes(selectedCategory));
    }

    // 按艺术家筛选
    if (selectedArtist) {
      result = result.filter((work) => work.artist === selectedArtist);
    }

    setFilteredWorks(result);
  }, [works, searchTerm, selectedCategory, selectedArtist]);

  // 重置所有筛选条件
  const resetFilters = () => {
    setSearchTerm('');
    setSelectedCategory('');
    setSelectedArtist('');
  };

  return (
    <MainLayout>
      <section className="py-16 bg-paper">
        <div className="container mx-auto px-4">
          <div className="text-center mb-12">
            <h1 className="text-4xl font-bold mb-4 text-ink">墨韵斋画廊</h1>
            <p className="text-lg text-ink-light max-w-2xl mx-auto">
              探索我们精选的书画作品收藏，感受中国传统艺术的魅力与精髓
            </p>
          </div>

          {/* 搜索和筛选区域 */}
          <div className="mb-12 bg-white p-6 rounded-sm shadow-sm">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {/* 搜索框 */}
              <div className="relative">
                <input
                  type="text"
                  placeholder="搜索作品名称或作者..."
                  className="w-full px-4 py-3 pl-10 border border-gray-200 rounded-sm focus:outline-none focus:ring-2 focus:ring-wood focus:border-transparent"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
                <svg xmlns="http://www.w3.org/2000/svg" className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
              </div>

              {/* 分类筛选 */}
              <div>
                <select
                  className="w-full px-4 py-3 border border-gray-200 rounded-sm focus:outline-none focus:ring-2 focus:ring-wood focus:border-transparent"
                  value={selectedCategory}
                  onChange={(e) => setSelectedCategory(e.target.value)}
                >
                  <option value="">所有分类</option>
                  {categories.map((category) => (
                    <option key={category} value={category}>
                      {category}
                    </option>
                  ))}
                </select>
              </div>

              {/* 艺术家筛选 */}
              <div>
                <select
                  className="w-full px-4 py-3 border border-gray-200 rounded-sm focus:outline-none focus:ring-2 focus:ring-wood focus:border-transparent"
                  value={selectedArtist}
                  onChange={(e) => setSelectedArtist(e.target.value)}
                >
                  <option value="">所有艺术家</option>
                  {artists.map((artist) => (
                    <option key={artist} value={artist}>
                      {artist}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* 筛选结果信息和重置按钮 */}
            <div className="mt-4 flex flex-col sm:flex-row justify-between items-start sm:items-center">
              <p className="text-ink-light text-sm mb-2 sm:mb-0">
                找到 {filteredWorks.length} 件作品
              </p>
              {(searchTerm || selectedCategory || selectedArtist) && (
                <button
                  onClick={resetFilters}
                  className="text-sm text-ink hover:text-wood transition-colors flex items-center"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                  重置筛选条件
                </button>
              )}
            </div>
          </div>

          {/* 作品网格布局 */}
          {filteredWorks.length > 0 ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
              {filteredWorks.map((work) => (
                <ArtworkCard key={work.id} work={work} />
              ))}
            </div>
          ) : (
            <div className="bg-white p-12 rounded-sm text-center">
              <svg xmlns="http://www.w3.org/2000/svg" className="h-16 w-16 text-gray-300 mx-auto mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
              <h3 className="text-xl font-medium text-ink mb-2">未找到作品</h3>
              <p className="text-ink-light mb-6">尝试调整搜索条件或重置筛选</p>
              <button
                onClick={resetFilters}
                className="bg-ink text-paper px-6 py-2 rounded-sm hover:bg-ink-light transition-colors"
              >
                重置筛选
              </button>
            </div>
          )}
        </div>
      </section>
    </MainLayout>
  );
};

export default Gallery;